package com.hx.myblog3.service;

import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;

import com.hx.myblog3.entity.Article;
import com.hx.myblog3.entity.ArticleType;
import com.hx.myblog3.repository.ArticleRepo;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;


@Component
public class ArticleService {
	@Autowired
	private ArticleRepo ar;
	
	//更新数据
	@Transactional
	public void update(Article article) {
		Article old=ar.findOne(article.getId());
		old.setTitle(article.getTitle());
		old.setImg(article.getImg());
		old.setAbstrct(article.getAbstrct());
		old.setContent(article.getContent());
		old.setAtype(article.getAtype());
	}
	
	//保存文章
	public Article save(Article article){
		return ar.save(article);
	}
	
	//通过id查找一条记录
	public Article findone(Integer id){
		return ar.findOne(id);
	}
	
	//通过id删除该条记录
	public void del(Integer id) {
		ar.delete(id);
	}
	
	//
	

	
	public List<Map<String, Object>> allArticles(){
		return ar.allArticle();
	}
	
	public List<Article> findAll(){
		return (List<Article>)ar.findAll();
	}
    
	public Page<Article> findPage(Integer pageNo){
		Pageable pageAble=new PageRequest(pageNo, 5);
		return ar.findAll(pageAble);
	}
	
	public Page<Article> findByAtype(Integer id,Integer pageNo){
		Pageable pageable=new PageRequest(pageNo, 5);
		ArticleType at=new ArticleType();
		at.setId(id);
		return ar.findByAtype(at, pageable);
	}
	
	public String pageToJsonString(Page<Article> page) {
		JsonConfig config=new JsonConfig();
		config.setJsonPropertyFilter(new PropertyFilter() {
			
			@Override
			public boolean apply(Object source, String name, Object value) {
				if (name.equals("atype")) {
					return true;
				}
				return false;
			}
		});
		JSONObject json=JSONObject.fromObject(page,config);
		JSONArray articles=(JSONArray)json.get("content");
		for (int i = 0; i < articles.size(); i++) {
			JSONObject atricle=(JSONObject)articles.get(i);
			atricle.remove("img");
			atricle.remove("content");
			atricle.remove("comments");	
		}
		return json.toString();
	}
	
}
